package com.zscat.mallplus.dms.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zscat.mallplus.annotation.SysLog;
import com.zscat.mallplus.dms.entity.DmsOrder;
import com.zscat.mallplus.dms.service.IDeviceService;
import com.zscat.mallplus.dms.service.IMealService;
import com.zscat.mallplus.dms.service.IQsgStoreService;
import com.zscat.mallplus.dms.service.WxMsgService;
import com.zscat.mallplus.qsg.QsgDevice;
import com.zscat.mallplus.qsg.QsgMeal;
import com.zscat.mallplus.qsg.QsgRechargeOrder;
import com.zscat.mallplus.qsg.QsgStore;
import com.zscat.mallplus.qsg.mapper.QsgDeviceMapper;
import com.zscat.mallplus.single.PayController;
import com.zscat.mallplus.sys.mapper.SysAppletSetMapper;
import com.zscat.mallplus.ums.entity.SysAppletSet;
import com.zscat.mallplus.ums.entity.UmsAdminMember;
import com.zscat.mallplus.ums.entity.UmsMember;
import com.zscat.mallplus.ums.service.IUmsAdminMemberService;
import com.zscat.mallplus.ums.service.IUmsMemberService;
import com.zscat.mallplus.utils.DateUtil;
import com.zscat.mallplus.utils.TemplateData;
import com.zscat.mallplus.utils.WXSubscribeMsgUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class WxMsgServiceImpl implements WxMsgService {

    private static Logger LOGGER = LoggerFactory.getLogger(WxMsgServiceImpl.class);

//    @Value("${wxpay.appId}")
//    private String wxH5Appid;
//    @Value("${wxpay.appSecret}")
//    private String wxH5Secret;
    @Autowired
    private IUmsAdminMemberService adminMemberService;
    @Autowired
    private IMealService mealService;
    @Autowired
    private IDeviceService deviceService;
    @Autowired
    private IUmsMemberService memberService;
    @Autowired
    private IQsgStoreService storeService;

    private final String wxH5Appid = "wx76bd72bfc117cbaf";
    private final String wxH5Secret = "4870b9b25e73848d6f74920c566787b3";

    @Override
    public void sendSubscribeMsg(DmsOrder order) {
        String accessToken = null;
        try {
            QsgStore store = storeService.getById(order.getStoreId());
            QueryWrapper qw = new QueryWrapper();
            qw.eq("store_id",order.getStoreId());
            List<UmsAdminMember> members = adminMemberService.list(qw);
            WXSubscribeMsgUtil wxSubscribeMsgUtil = WXSubscribeMsgUtil.getInstance();
            accessToken = wxSubscribeMsgUtil.getAccessToken(wxH5Appid,wxH5Secret);
            String templateId = "B79fzaNcHr9j2LB8gz00szHQkzeB0-SH_pA5BykKx6U";
            Map<String, TemplateData> param = new HashMap<>();
            QsgDevice device = deviceService.getById(order.getDeviceId());
            String first = "您的房间["+device.getMachineName()+"]有一个新订单";
            if (null!=members&&members.size()>0){
                for (UmsAdminMember member : members
                ) {
                    param.put("thing2", new TemplateData(store.getName(), "#565656"));
                    param.put("amount7", new TemplateData(order.getPrice().toString(), "#565656"));
                    param.put("time4", new TemplateData(order.getStartTime(), "#565656"));
                    param.put("time8", new TemplateData(order.getEndTime(), "#565656"));
                    String notifyUrl = "http://m.quedou.cn/pages/order/orderDetail?orderId="+order.getId();
                    URLEncoder.encode(notifyUrl,"utf-8");
                    JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(param));
                    String suc = WXSubscribeMsgUtil.sendWechatMsgToUser(member.getWeixinOpenid(), templateId, notifyUrl, jsonObject, accessToken);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void sendCannelMsg(DmsOrder order) {
        QsgStore store = storeService.getById(order.getStoreId());
        String accessToken = null;
        try {
            QueryWrapper qw = new QueryWrapper();
            qw.eq("store_id",order.getStoreId());
            List<UmsAdminMember> members = adminMemberService.list(qw);
            WXSubscribeMsgUtil wxSubscribeMsgUtil = WXSubscribeMsgUtil.getInstance();
            accessToken = wxSubscribeMsgUtil.getAccessToken(wxH5Appid,wxH5Secret);
            String templateId = "HuQY49ZxIgupR2Ou_ktDhHj7J7_19y9GLmFs8R7Z1EI";
            Map<String, TemplateData> param = new HashMap<>();
            String time = order.getStartTime();
            QsgMeal meal = mealService.getById(order.getMealId());
            if (null!=members&&members.size()>0){
                for (UmsAdminMember member : members
                ) {
                    param.put("thing2", new TemplateData(store.getName(), "#565656"));
                    param.put("amount6", new TemplateData(order.getPrice().toString(), "#565656"));
                    param.put("time4", new TemplateData(DateUtil.dateToString(new Date(),"yyyy/MM/dd HH:mm"), "#565656"));
                    param.put("time10", new TemplateData(order.getStartTime(), "#565656"));
                    param.put("thing12", new TemplateData(meal.getMealName(), "#565656"));
                    String notifyUrl = "http://m.quedou.cn/pages/order/orderDetail?orderId="+order.getId();
                    JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(param));
                    String suc = WXSubscribeMsgUtil.sendWechatMsgToUser(member.getWeixinOpenid(), templateId, notifyUrl, jsonObject, accessToken);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void sendDasaoMsg(DmsOrder order) {
        QsgStore store = storeService.getById(order.getStoreId());
        String accessToken = null;
        try {
            QueryWrapper qw = new QueryWrapper();
            qw.eq("store_id",order.getStoreId());
            List<UmsAdminMember> members = adminMemberService.list(qw);
            WXSubscribeMsgUtil wxSubscribeMsgUtil = WXSubscribeMsgUtil.getInstance();
            accessToken = wxSubscribeMsgUtil.getAccessToken(wxH5Appid,wxH5Secret);
            String templateId = "sXnnOU8_5t4eCViY68nhpeY4YXyZRnsuwgeeV5Kk5pU";
            QsgDevice device = deviceService.getById(order.getDeviceId());
            Map<String, TemplateData> param = new HashMap<>();
            String time = order.getEndTime();
            QsgMeal meal = mealService.getById(order.getMealId());
            if (null!=members&&members.size()>0){
                for (UmsAdminMember member : members
                ) {
                    param.put("time9", new TemplateData(order.getStartTime(), "#565656"));
                    param.put("time10", new TemplateData(order.getEndTime(), "#565656"));
                    param.put("character_string6", new TemplateData(order.getOrderSn(), "#565656"));
                    param.put("thing15", new TemplateData(store.getName(), "#ff9662"));
                    JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(param));
                    String suc = WXSubscribeMsgUtil.sendWechatMsgToUser(member.getWeixinOpenid(), templateId, "", jsonObject, accessToken);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void sendRecharge(QsgRechargeOrder order,Integer integral) {
        log.info("积分:{}",integral);
        log.info("店铺id:{}",order.getStoreId());
        QsgStore store = storeService.getById(order.getStoreId());
        String accessToken = null;
        try {
            QueryWrapper qw = new QueryWrapper();
            qw.eq("store_id",order.getStoreId());
            List<UmsAdminMember> members = adminMemberService.list(qw);
            WXSubscribeMsgUtil wxSubscribeMsgUtil = WXSubscribeMsgUtil.getInstance();
            accessToken = wxSubscribeMsgUtil.getAccessToken(wxH5Appid,wxH5Secret);
            String templateId = "MDlXbZrMpJYJP0GXoNQStDc2mQ9UZIgT4Uah5Zj4Crs";
            Map<String, TemplateData> param = new HashMap<>();
            if (null!=members&&members.size()>0){
                for (UmsAdminMember member : members
                ) {
                    param.put("amount2", new TemplateData(order.getPrice().toString(), "#565656"));
                    param.put("amount3", new TemplateData(new BigDecimal(integral).divide(new BigDecimal("100")).toString(), "#565656"));
                    param.put("time4", new TemplateData(DateUtil.dateToStr(order.getCreateDatetime(),"yyyy-MM-dd HH:mm"), "#565656"));
                    param.put("character_string5", new TemplateData(order.getOrderSn(), "#565656"));
                    param.put("thing8", new TemplateData(store.getName(), "#565656"));
                    JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(param));
                    String suc = WXSubscribeMsgUtil.sendWechatMsgToUser(member.getWeixinOpenid(), templateId, "", jsonObject, accessToken);
                    log.info("消息推送错误:{}",suc);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
